package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

func main() {
	fileName := "/Users/jumao/go/src/go_code/go_learning/chapter12_document_function/123.txt"
	//os.O_WRONLY，这个参数会从文件开头开始写，原文件被覆盖，未被覆盖的原文件会保留
	//file, err := os.OpenFile(fileName, os.O_WRONLY, 0666)

	//os.O_TRUNC是只清空文件,清空并写入需要两个参数: os.O_WRONLY|os.O_TRUNC
	//file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC, 0666)

	//os.O_APPEND追加写入到后面,需要追加写也是两个参数os.O_APPEND|os.O_WRONLY
	//file, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, 0666)

	//读写文件并追加写os.O_RDWR|os.O_APPEND
	file, err := os.OpenFile(fileName, os.O_RDWR|os.O_APPEND, 0666)
	defer file.Close()
	if err != nil {
		fmt.Printf("open file err=%v\n", file)
	}
	reader := bufio.NewReader(file)
	for {
		str, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		fmt.Printf(str)
	}

	str := "beijing\r\n"
	wr := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		wr.WriteString(strconv.Itoa(i) + "." + str)
	}
	//将缓存写入磁盘
	wr.Flush()

}
